package com.zhiyume.shiro;

import com.zhiyume.dao.api.TAdminMapper;
import com.zhiyume.dao.entity.TAdminCriteria;
import com.zhiyume.dao.entity.TAdminSys;
import com.zhiyume.exception.IncorrectPasswordException;
import com.zhiyume.service.AdminService;
import com.zhiyume.service.util.DateUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class ShiroRealmImpl extends AuthorizingRealm {
    private Logger logger = LogManager.getLogger(ShiroRealmImpl.class);
    @Autowired
    private TAdminMapper tAdminMapper;
    @Autowired
    private AdminService adminService;
    /**
     * 提供用户信息返回权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        /** 获取用户对象 */
        TAdminSys sysUser = (TAdminSys) principalCollection.fromRealm(getName()).iterator()
                .next();
        if (sysUser == null) {
            logger.info("获取鉴权信息：获取用户信息为空");
        }
        try {
            logger.info("获取鉴权信息：开始获取登录用户"+ sysUser.getUserName());
            SimpleAuthorizationInfo info = adminService.simpleAuthorizationInfo(sysUser);
            logger.info("获取鉴权信息：成功获取登录用户【{}】鉴权信息"+ sysUser.getUserName());
            return info;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取鉴权信息：获取登录用户【{}】鉴权信息时发生异常：{}"+
                    sysUser.getUserName()+e.getMessage());
            throw new AccountException(e.getMessage(), e);
        }
    }

    /**
     * 提供账户信息返回认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("身份认证方法：MyShiroRealm.doGetAuthenticationInfo()");
        ShiroToken token = (ShiroToken) authenticationToken;
        TAdminSys user = adminService.selectAdminByUserName(token.getUsername());
        if (null == user) {
            throw new IncorrectPasswordException("帐号或密码不正确！");
        }else if(!user.getPassword().equals(String.valueOf(token.getPassword()))){
            /**
             * 如果用户的status为禁用。那么就抛出<code>DisabledAccountException</code>
             */
            throw new IncorrectPasswordException("帐号或密码不正确！");
        } else{
            //更新登录时间 last login time
            user.setLastLoginTime(DateUtil.getNow());
            TAdminCriteria example = new TAdminCriteria();
            TAdminCriteria.Criteria c = example.createCriteria();
            c.andUserNameEqualTo(token.getUsername());
            tAdminMapper.updateByExample(user,example);
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());

    }
}
